package com.badibadi.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalBitmap;

import org.json.JSONException;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.badibadi.activity.AfterLandingActivity;
import com.badibadi.activity.ChoiceCrewActivity;
import com.badibadi.activity.ClubHomepageActivity;
import com.badibadi.activity.CreationNewClub4Activity;
import com.badibadi.activity.MyDataActivity;
import com.badibadi.activity.SeeOtherPeopleSpaceActivity;
import com.badibadi.fragment.AfterLandingAddFriendsMsgItemFragment0.XListView1Adapter____1;
import com.badibadi.fragment.AfterLandingMessageItem01.ViewHolder;
import com.badibadi.infos.Invite_Friend_Model;
import com.badibadi.infos.Pre_message_total;
import com.badibadi.infos.Results;
import com.badibadi.mytools.CalendarTools;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.HtmlUtils;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.SystemUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.libjph.util.StringUtil;
//import com.lidroid.xutils.util.LogUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

///**第一个fragment 配对 *///after_landing_freinds00_1  after_landing_friends00_xlistView after_peidui
public class AfterLandingMessageItem00 extends BaseAppFragment implements
		IXListViewListener {
	// TODO Auto-generated method stub
	private String TAG = "AfterLandingMessageItem00";
	private XListView1Adapter____1 x1Adapter;
	private XListView xListView1;
	private int Page;
	private Results results, results2;
	private List<Pre_message_total> mList;
	private List<Pre_message_total> list;
	// private FinalBitmap finalBitmap;
	private int pageNum = 6;
	private String uid = "1";
	private Message message;
	private Bundle bundle;
	private DisplayImageOptions options;
	int a = 1;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(getActivity());
				onLoad();
				try {
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}

				break;
			case 2:
				Utils.ExitPrgress(getActivity());
				try {
					mList.addAll(list);
					x1Adapter.notifyDataSetChanged();
					onLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				Utils.ExitPrgress(getActivity());
				try {
					onLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}

				try {
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}
				break;
			case 4:
				Utils.ExitPrgress(getActivity());
				try {
					Utils.showMessage(getActivity(), results2.getRetmsg());
//					Intent intent = new Intent();
//					intent.putExtra("res", msg.getData().getString("res"));
//					setResult(21, intent);
//					finish();
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}
			default:
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mList = new ArrayList<Pre_message_total>();
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();

		x1Adapter = new XListView1Adapter____1();
		// finalBitmap = FinalBitmap.create(getActivity());
		uid = getArguments().getString("uid");

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.after_landing_freinds00_1, null);
		InitMyXListView1(view);
		return view;
	}

	public void InitMyXListView1(View view) {
		Page = 0;
		Constants.Invite_handler = mHandler;
		xListView1 = (XListView) view
				.findViewById(R.id.after_landing_friends00_xlistView);
		xListView1.setXListViewListener(this);
		xListView1.setPullLoadEnable(true);
		xListView1.setPullRefreshEnable(true);
		xListView1.setAdapter(x1Adapter);
		xListView1.startLoadMore();
	}

	private void LoadingMessage(final int page) {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				String lang = com.badibadi.mytools.Dialog
						.getSystemLanguageTypegrzx(getActivity());
				list = new ArrayList<Pre_message_total>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", uid);
				map.put("type", "message_peidui");
				map.put("page", page);
				map.put("lang", lang);
				map.put("pageNum", pageNum);
				String invite_content = Utils.sendRequest(map,
						Constants.BadiUrl + "message_total");
				//
				if (invite_content != null) {
					results = Utils.checkResult_NNN(getActivity(),
							invite_content);
					if (results != null && !results.getRetmsg().equals("null")) {
						//
						try {
							list = JSONUtils.getListByJsonString(
									results.getRetmsg(),
									Pre_message_total.class);

							mHandler.sendEmptyMessage(2);
						} catch (Exception e) {
							// TODO Auto-generated catch block

							mHandler.sendEmptyMessage(3);
						}
					} else {
						if (page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						mHandler.sendEmptyMessage(3);
					}
				} else {
					if (page > 1) {
						--Page;
					} else {
						Page = 1;
					}
					mHandler.sendEmptyMessage(1);
				}

			}
		});
	}

	protected void onLoad() {
		xListView1.stopRefresh();
		xListView1.stopLoadMore();
		xListView1.setRefreshTime(""
				+ getResources().getString(R.string.ganggang));
	}

	class XListView1Adapter____1 extends BaseAdapter {
		private static final int MAX_TEXT = 8;

		// private DisplayImageOptions options;

		public XListView1Adapter____1() {
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.ic_stub)
					.showImageForEmptyUri(R.drawable.noimage)
					.showImageOnFail(R.drawable.noimage).cacheInMemory()
					.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5))
					.build();
		}

		@Override
		public int getCount() {

			return mList.size();
		}

		@Override
		public int getItemViewType(int position) {
			// TODO Auto-generated method stub

			if (mList.get(position).getType().equals("usertoclub")) {
				return 0; // usertoclub
			} else if (mList.get(position).getType().equals("clubtouser")) {
				return 1; // clubtouser
			}
			return -1;
		}

		@Override
		public int getViewTypeCount() {
			// TODO Auto-generated method stub
			return 3;
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			int imageWH = 55;
			LayoutInflater mInflater = LayoutInflater.from(getActivity());

			ViewHolder holder;
			int type = getItemViewType(position);

			if (convertView == null) {
				holder = new ViewHolder();
				switch (type) {
				case 0:// 别人有相同兴趣爱好的人配对给我
					convertView = mInflater.inflate(
							R.layout.after_peidui_me_to_club, parent, false);
					holder.nickName = (TextView) convertView
							.findViewById(R.id.nickName);//
					holder.name = (TextView) convertView
							.findViewById(R.id.name);
					holder.typeName = (TextView) convertView
							.findViewById(R.id.typeName);// 俱乐部类型
					holder.motto = (TextView) convertView
							.findViewById(R.id.motto);
					holder.head = (ImageView) convertView
							.findViewById(R.id.head);
					holder.time = (TextView) convertView
							.findViewById(R.id.time);
//					holder.invent = (TextView) convertView
//							.findViewById(R.id.invent);
					break;
				case 1:// 俱乐部配对给我
					convertView = mInflater.inflate(
							R.layout.after_peidui_club_to_me, parent, false);
					holder.head = (ImageView) convertView
							.findViewById(R.id.head);
					holder.name = (TextView) convertView
							.findViewById(R.id.name);
					holder.typeName = (TextView) convertView
							.findViewById(R.id.typeName);// 俱乐部类型
					holder.time = (TextView) convertView
							.findViewById(R.id.time);
					holder.info = (TextView) convertView
							.findViewById(R.id.info);// 宗旨
//					holder.invent = (TextView) convertView
//							.findViewById(R.id.invent);

					break;
				}
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			if (type == 0) {
				if (!StringUtil.isNullOrEmpty(mList.get(position).getHead())) {
//					holder.invent.setVisibility(View.VISIBLE);
					try {
						// 头像
						ImageLoader.getInstance().displayImage(
								Constants.BadiDownImgUrl + "/"
										+ mList.get(position).getHead()
										+ Constants.appPhoto4img, holder.head,
								options);
						//
					} catch (Exception e) {
						// TODO: handle exception
					}
				} else {
					Bitmap bmp = BitmapFactory.decodeResource(getResources(),
							R.drawable.noimage);
					holder.head.setImageBitmap(bmp);
				}
				// 设置邀请
//				try {
//					holder.invent.setOnClickListener(new OnClickListener() {
//						
//
//						@Override
//						public void onClick(View v) {
//							if (a == 1) {
//								if (!StringUtil.isNullOrEmpty(mList.get(position).getId())) {
//									message = new Message();
//									bundle = new Bundle();
//									message.what = 4;
////									   
//									bundle.putString("res",
//											mList.get(position).getId().substring(0, mList.get(position).getId().length() - 1));
//
//									message.setData(bundle);
//									mHandler.sendMessage(message);
//									System.out.println(message);
//								}
//								Toast toast = Toast.makeText(
//										getActivity(),
//										getResources().getString(
//												R.string.l_xb67),
//										Toast.LENGTH_SHORT);
//								toast.setGravity(Gravity.CENTER, 0, 0);
//								toast.show();
//								a++;
//								
//							} else {
//								Toast toast = Toast.makeText(
//										getActivity(),
//										"已邀请过，请勿重复邀请",
//										Toast.LENGTH_SHORT);
//								toast.setGravity(Gravity.CENTER, 0, 0);
//								toast.show();
//								a--;
//							}
//						}
//					});
//				} catch (Exception e) {
//					// TODO: handle exception
//				}

				holder.head.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!StringUtil.isNullOrEmpty(mList.get(position)
								.getId())) {
							if (mList.get(position).getId()
									.equals(Utils.getUid(getActivity()))) {
								Intent intent = new Intent(getActivity(),
										MyDataActivity.class);
								startActivity(intent);
							} else {
								Intent intent = new Intent(getActivity(),
										SeeOtherPeopleSpaceActivity.class);
								intent.putExtra("friend_id", mList
										.get(position).getId());
								startActivity(intent);
							}
						}
					}
				});
				try {
					if (mList.get(position).getTypeName() != null) {
						holder.typeName.setText(""
								+ mList.get(position).getTypeName());
					} else {
						holder.typeName.setText("");
					}
				} catch (Exception e) {
					// TODO: handle exception
				}

				holder.nickName.setText("" + mList.get(position).getNickName());
				try {
					holder.name.setText("" + mList.get(position).getName());
				} catch (Exception e) {
					// TODO: handle exception
				}
				holder.nickName.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!StringUtil.isNullOrEmpty(mList.get(position)
								.getId())) {
							if (mList.get(position).getId()
									.equals(Utils.getUid(getActivity()))) {
								Intent intent = new Intent(getActivity(),
										AfterLandingActivity.class);
								startActivity(intent);
							} else {
								Intent intent = new Intent(getActivity(),
										SeeOtherPeopleSpaceActivity.class);
								intent.putExtra("friend_id", mList
										.get(position).getId());
								startActivity(intent);
							}
						}
					}
				});
				holder.name.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!StringUtil.isNullOrEmpty(mList.get(position)
								.getCid())) {
							Intent intent = new Intent(getActivity(),
									ClubHomepageActivity.class);
							intent.putExtra("cid", mList.get(position).getCid());
							startActivity(intent);
						}

					}
				});
				try {
					holder.time.setText(""
							+ CalendarTools.getTimeChangeToString(
									getActivity(), mList.get(position)
											.getTime()));
				} catch (Exception e) {
					// TODO: handle exception
				}

				holder.motto.setEllipsize(TruncateAt.END);
				holder.motto.setMaxEms(MAX_TEXT);
				holder.motto.setSingleLine(true);
				// holder.motto.setText(""+mList.get(position).getMotto());
				new HtmlUtils(getActivity(), holder.motto, mList.get(position)
						.getMotto()).showTextView();
			} else if (type == 1) {

				if (!StringUtil.isNullOrEmpty(mList.get(position).getLogo())) {
					try {
						// 头像
						ImageLoader.getInstance().displayImage(
								Constants.BadiDownImgUrl + "/"
										+ mList.get(position).getLogo()
										+ Constants.appPhoto4img, holder.head,
								options);
					} catch (Exception e) {
						// TODO: handle exception
					}
				} else {
					Bitmap bmp = BitmapFactory.decodeResource(getResources(),
							R.drawable.noimage);
					holder.head.setImageBitmap(bmp);
				}
				holder.head.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!StringUtil.isNullOrEmpty(mList.get(position)
								.getCid())) {
							Intent intent = new Intent(getActivity(),
									ClubHomepageActivity.class);
							intent.putExtra("cid", mList.get(position).getCid());
							startActivity(intent);
						}

					}
				});

				if (mList.get(position).getTypeName() != null)
					holder.typeName.setText(""
							+ mList.get(position).getTypeName());
				else
					holder.typeName.setText("");

				holder.name.setText("" + mList.get(position).getName());
				try {
					holder.time.setText(""
							+ CalendarTools.getTimeChangeToString(
									getActivity(), mList.get(position)
											.getTime()));
				} catch (Exception e) {
					// TODO: handle exception
				}

				holder.name.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!StringUtil.isNullOrEmpty(mList.get(position)
								.getCid())) {
							Intent intent = new Intent(getActivity(),
									ClubHomepageActivity.class);
							intent.putExtra("cid", mList.get(position).getCid());
							startActivity(intent);
						}
					}
				});

				// holder.info.setText(""+mList.get(position).getInfo());
				holder.info.setEllipsize(TruncateAt.END);
				holder.info.setMaxEms(MAX_TEXT);
				holder.info.setSingleLine(true);
				// holder.info.setMaxLines(3);
				holder.info.setText("" + mList.get(position).getInfo());
				// new HtmlUtils(getActivity(), holder.info, mList.get(position)
				// .getInfo()).showTextView();
			}

			// //昵称
			// holder.nickName.setText(""+mList.get(position).getNickName());
			// //俱乐部名称
			// holder.name.setText(""+mList.get(position).getName());
			// //座右铭
			// holder.motto.setText(""+mList.get(position).getMotto());
			// //头像
			// finalBitmap.display(holder.head,
			// Constants.BadiDownImgUrl+"/"+mList.get(position).getHead(),DisplayUtil.dip2px(getActivity(),
			// imageWH),DisplayUtil.dip2px(getActivity(), imageWH));
			// //俱乐部名称
			// holder.typeName.setText(""+mList.get(position).getTypeName());
			// //发布时间
			// holder.time.setText(""+mList.get(position).getTime());
			return convertView;
		}
	}

	static class ViewHolder {
		// 别人匹配我的俱乐部
		public String id;// 用户id
		public ImageView head;// 用户头像
		public TextView nickName;// 用户昵称
		public TextView motto;// 用户座右铭
		public String cid;// 我主动匹配到的俱乐部id
		public TextView name;// 俱乐部名字
		public TextView typeName;// 俱乐部类型;//俱乐部类型
		public TextView time;// 匹配时间
		public String is_show;// 是否查看过 0：未查看，1：已查看
		public String type;// usertoclub表示别人匹配我的俱乐部 clubtouser别人创建的俱乐部主动匹配我的兴趣
		// 我匹配别人的俱乐部
		// public String cid;//俱乐部主动匹配到我的俱乐部id
		// public String name;//俱乐部名字
		public String logo;// 俱乐部logo
		public TextView info;// 俱乐部介绍
		public TextView invent;// 邀请
		// public String time;//匹配时间
		// public String typeName;//俱乐部类型
		// public String is_show;//是否查看过 0：未查看，1：已查看
		// public String type;//usertoclub表示别人匹配我的俱乐部 clubtouser别人创建的俱乐部主动匹配我的兴趣
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		Page = 1;
		mList = new ArrayList<Pre_message_total>();
		LoadingMessage(Page);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		LoadingMessage(++Page);
	}
}